package com.hwy.simple.chart.http

import android.os.Handler
import android.os.Looper
import android.util.Log
import okhttp3.*
import java.io.IOException

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/5/11 14:26
 * 说明:
 * =======================================
 */
object HttpUtil {

    private const val TAG = "HttpUtil"

    private val okhttpClient by lazy {
        OkHttpClient()
    }

    private val handler by lazy {
        Handler(Looper.getMainLooper())
    }

    fun request(url: String?, callback: HttpCallback?) {
        url?.run {
            val request = Request.Builder()
                .url(this)
                .get()
                .build()
            okhttpClient.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    Log.d(TAG, "request failure, ${e.message}")
                    callback?.onFailure(e.message)
                }

                override fun onResponse(call: Call, response: Response) {
                    if (response.isSuccessful) {
                        response.body?.string()?.run {
                            Log.d(TAG, "request success")
                            handler.post { callback?.onSuccess(this) }
                            return
                        }
                    }
                    callback?.onFailure("request failure")
                }

            })
        }
    }

    interface HttpCallback {

        fun onSuccess(json: String?)

        fun onFailure(msg: String?)

    }

}